package tchk.xyz.lingyuntutorminiprogram.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tchk.xyz.lingyuntutorminiprogram.dto.WithdrawalAuditDTO;
import tchk.xyz.lingyuntutorminiprogram.entity.SysUser;
import tchk.xyz.lingyuntutorminiprogram.entity.WalletTransaction;
import tchk.xyz.lingyuntutorminiprogram.exception.CustomException;
import tchk.xyz.lingyuntutorminiprogram.mapper.WalletTransactionMapper;
import tchk.xyz.lingyuntutorminiprogram.service.IUserService;
import tchk.xyz.lingyuntutorminiprogram.service.IWalletTransactionService;

@Service
public class WalletTransactionServiceImpl extends ServiceImpl<WalletTransactionMapper, WalletTransaction> implements IWalletTransactionService {

    @Autowired
    private IUserService userService;

    @Override
    public IPage<WithdrawalAuditDTO> getPendingWithdrawals(IPage<WithdrawalAuditDTO> page) {
        return this.baseMapper.findPendingWithdrawals(page);
    }

    @Override
    @Transactional
    public void auditWithdrawal(Long transactionId, Boolean isApproved) {
        WalletTransaction transaction = this.getById(transactionId);
        if (transaction == null || !"withdrawal_pending".equals(transaction.getType())) {
            throw new CustomException("提现申请不存在或状态不正确");
        }

        if (isApproved) {
            // 审核通过，状态变为已完成
            transaction.setType("withdrawal_completed");
            this.updateById(transaction);
            // 此处应有真实的打款操作，我们模拟为成功
        } else {
            // 审核驳回，需要将冻结的金额返还给用户钱包
            SysUser user = userService.getById(transaction.getUserId());
            user.setBalance(user.getBalance().add(transaction.getAmount().abs()));
            userService.updateById(user);

            // 更新流水状态为已驳回
            transaction.setType("withdrawal_rejected");
            this.updateById(transaction);
        }
    }

    @Override
    public IPage<WithdrawalAuditDTO> getWithdrawalsByStatus(IPage<WithdrawalAuditDTO> page, String status) {
        return this.baseMapper.findWithdrawalsByStatus(page, status);
    }
}